#include "resetdialog.h"
#include "ui_resetdialog.h"
#include <QDebug>
#include <QRegularExpression>
#include "httpmgr.h"

ResetDialog::ResetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ResetDialog)
{
    ui->setupUi(this);
    connect(ui->return_btn,&QPushButton::clicked,this,&ResetDialog::signals_switch_to_login);
    ui->newpwd_lineEdit->setEchoMode(QLineEdit::Password);

    ui->user_lineEdit->setPlaceholderText("请输入用户名");
    ui->email_lineEdit->setPlaceholderText("请输入邮箱");
    ui->newpwd_lineEdit->setPlaceholderText("请输入密码");
    ui->varify_lineEdit->setPlaceholderText("请输入验证码");

    ui->tip_label->clear();

    connect(ui->user_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkUserValid();
    });
    connect(ui->email_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkEmailValid();
    });
    connect(ui->newpwd_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkPassValid();
    });
    connect(ui->varify_lineEdit,&QLineEdit::editingFinished,this,[this](){
       checkVarifyValid();
    });

    initHttpHandlers();
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reset_mod_finish,this,
            &ResetDialog::slot_reset_mod_finish);
}

ResetDialog::~ResetDialog()
{
    qDebug()<<"~ResetDialog()";
    delete ui;
}

void ResetDialog::initHttpHandlers()
{
    //注册验证码回包的逻辑
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE,[this](const QJsonObject& jsonObject){
       int error = jsonObject["error"].toInt();
       if(error != ErrorCodes::SUCCESS){
           showTip("参数错误",false);
           qDebug()<<"ResetDialog::initHttpHandlers():参数错误";
           return;
       }
       QString email = jsonObject["email"].toString();
       qDebug()<<"email is "<<email;
       showTip("验证码已经发送，请注意查收",true);
    });

    //注册重置密码逻辑
    _handlers.insert(ReqId::ID_RESET_PWD,[this](QJsonObject jsonObj){
       int error = jsonObj["error"].toInt();
       if(error != ErrorCodes::SUCCESS){
           showTip("参数错误",false);
           return;
       }
       showTip("重置成功，再次点击确认按钮返回登录界面",true);
    });

}


void ResetDialog::showTip(const QString& str,bool ok)
{
    ui->tip_label->setText(str);
    if(ok){
        ui->tip_label->setProperty("state","normal");
    }
    else{
        ui->tip_label->setProperty("state","error");
    }
    repolish(ui->tip_label);
}

void ResetDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips,false);
}

void ResetDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->tip_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

bool ResetDialog::checkUserValid()
{
    if(ui->user_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,"用户名不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool ResetDialog::checkPassValid()
{
    QString pass = ui->newpwd_lineEdit->text();
    if(pass.length()<6 || pass.length()>15){
        //密码长度不符合要求
        AddTipErr(TipErr::TIP_PWD_ERR,"密码长度应该为6-15位");
        return false;
    }
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_PWD_ERR,"不能包含非法字符");
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    return true;
}

bool ResetDialog::checkEmailValid()
{
    QString email = ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|\_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,"邮箱地址不正确");
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool ResetDialog::checkVarifyValid()
{
    QString pass = ui->varify_lineEdit->text();
    if(pass.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR,"验证码不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}


void ResetDialog::on_get_btn_clicked()//获取验证码按钮
{
    auto email = ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|\_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if(match){
        //发送hhtp请求验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_varifycode"),
                                            json_obj,ReqId::ID_GET_VARIFY_CODE,Modules::REGISTERMOD);
    }else{
        showTip("邮箱格式错误",false);
    }
}

void ResetDialog::slot_reset_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS){
        showTip("网络请求错误",false);
        return;
    }
    //解析json字符串，转化成QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull()){
        showTip("json解析失败",false);
        return;
    }
    if(!jsonDoc.isObject()){
        showTip("json解析失败",false);
        return;
    }
    //根据id执行对应的回调函数
    _handlers[id](jsonDoc.object());
}

void ResetDialog::on_sure_btn_clicked()
{
    if(ui->tip_label->text()=="重置成功，再次点击确认按钮返回登录界面"){
        emit signals_switch_to_login();
        return;
    }
    if(!checkUserValid()||!checkPassValid()||!checkEmailValid()||!checkVarifyValid()){
        return;
    }
    QJsonObject json_obj;
    json_obj["user"] = ui->user_lineEdit->text();
    json_obj["email"] = ui->email_lineEdit->text();
    json_obj["passwd"] = xorString(ui->newpwd_lineEdit->text());
    json_obj["varifycode"] = ui->varify_lineEdit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/reset_pwd"),
                                        json_obj,ReqId::ID_RESET_PWD,Modules::RESETMOD);
}
